package cn.xinyangtong.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 获取CSESSIONID
 * Created by fengbo on 2017/8/3.
 */
public class RequestUtil {

    //获取
    public static String getCSessionId(
            HttpServletRequest request, HttpServletResponse response) {
        //取出cookie
        Cookie[] cookies = request.getCookies();
        //判断cookie中是否有CSESSIONID
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (ConstantsUtil.CSESSIONID.equals(cookie.getName())) {
                    //有 直接使用
                    return cookie.getValue();
                }
            }
        }
        //没有 创建一个 并保存到cookie中
        String csessionId = UUID.randomUUID().toString().replaceAll("-", "");
        Cookie cookie = new Cookie(ConstantsUtil.CSESSIONID, csessionId);
        //设置存活时间 -1 关闭浏览器销毁 0 销毁 >0 存活时间
        cookie.setMaxAge(-1);
        //设置路径
        cookie.setPath("/");
        //设置跨域
//        cookie.setDomain(".jd.com");
        response.addCookie(cookie);
        return csessionId;
    }
}
